package com.deanlib.cabinet.app;

import android.app.Application;
import android.app.usage.ExternalStorageStats;
import android.content.Context;
import android.os.Environment;

import com.deanlib.cabinet.R;
import com.deanlib.cabinet.data.model.ResourceCache;
import com.deanlib.cabinet.data.network.NetWorkManager;
import com.deanlib.cabinet.utils.OssManager;
import com.deanlib.plantern.Plantern;
import com.deanlib.plantern.utils.PopupUtils;
import com.elvishew.xlog.LogConfiguration;
import com.elvishew.xlog.LogLevel;
import com.elvishew.xlog.XLog;
import com.elvishew.xlog.flattener.PatternFlattener;
import com.elvishew.xlog.formatter.message.json.DefaultJsonFormatter;
import com.elvishew.xlog.internal.Platform;
import com.elvishew.xlog.printer.AndroidPrinter;
import com.elvishew.xlog.printer.ConsolePrinter;
import com.elvishew.xlog.printer.Printer;
import com.elvishew.xlog.printer.file.FilePrinter;
import com.elvishew.xlog.printer.file.backup.FileSizeBackupStrategy2;
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy;
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator;
import com.elvishew.xlog.printer.file.writer.Writer;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.tencent.mmkv.MMKV;

import java.io.File;
import java.util.List;


/**
 * Created by Dean on 2022/6/13
 */
public class App extends Application {

    //static 代码段可以防止内存泄露
    static {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                layout.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);//全局设置主题颜色
                return new ClassicsHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });
    }

    @Override
    public void onCreate() {
        super.onCreate();

        initLog();

        Plantern.init(this, Constants.IS_DEBUG);
        NetWorkManager.getInstance().init(this);
        MMKV.initialize(this);

        initData();

    }

    private void initData(){
        String[] createDirArr = {
                ResourceCache.getCacheDir(),
                OssManager.getCompressDir()
        };
        for (String dirPath : createDirArr) {
            File file = new File(dirPath);
            if (!file.exists()) {
                if (!file.mkdirs()) {
                    PopupUtils.sendToast(R.string.create_cache_dir_fail);
                }
            }
        }
    }

    private void initLog() {
        String logPath = getExternalCacheDir().getPath() + "/log";
        LogConfiguration config = new LogConfiguration.Builder()
//                .logLevel(BuildConfig.DEBUG ? LogLevel.ALL             // 指定日志级别，低于该级别的日志将不会被打印，默认为 LogLevel.ALL
//                        : LogLevel.ERROR)
                .tag("CABINET-LOG")                                         // 指定 TAG，默认为 "X-LOG"
                .enableThreadInfo()                                    // 允许打印线程信息，默认禁止
                .enableStackTrace(10)                                   // 允许打印深度为 2 的调用栈信息，默认禁止
                .jsonFormatter(new DefaultJsonFormatter())                  // 指定 JSON 格式化器，默认为 DefaultJsonFormatter
                .build();

        Printer androidPrinter = new AndroidPrinter(true);         // 通过 android.util.Log 打印日志的打印器
        Printer consolePrinter = new ConsolePrinter();             // 通过 System.out 打印日志到控制台的打印器
        Printer filePrinter = new FilePrinter                      // 打印日志到文件的打印器
                .Builder(logPath)                             // 指定保存日志文件的路径
                .fileNameGenerator(new DateFileNameGenerator())        // 指定日志文件名生成器，默认为 ChangelessFileNameGenerator("log")
                .backupStrategy(new FileSizeBackupStrategy2(1024 * 1024 * 10, FileSizeBackupStrategy2.NO_LIMIT))             // 指定日志文件备份策略，默认为 FileSizeBackupStrategy(1024 * 1024)
                .cleanStrategy(new FileLastModifiedCleanStrategy(7 * 24 * 3600 * 1000))     // 指定日志文件清除策略，默认为 NeverCleanStrategy()
                .flattener(new PatternFlattener("{d yyyy-MM-dd HH:mm:ss.SSS} {L}/{t}: {m}"))
                .build();
        XLog.init(                                                 // 初始化 XLog
                androidPrinter,                                        // 添加任意多的打印器。如果没有添加任何打印器，会默认使用 AndroidPrinter(Android)/ConsolePrinter(java)
                filePrinter
        );
    }
}
